package com.jus.player.activity.my;

import static com.jus.player.api.OkHttpHelper._DATA;
import static com.jus.player.config.AppConfig.PRODUCT_ID_VIP_MONTH;
import static com.jus.player.config.AppConfig.PRODUCT_ID_VIP_SEASON;
import static com.jus.player.config.AppConfig.PRODUCT_ID_VIP_YEAR;
import static com.jus.player.util.CommonUtils.showToast;
import static com.jus.player.util.CommonUtils.showToastPos;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.alibaba.fastjson2.JSONObject;
import com.jus.player.R;
import com.jus.player.activity.BaseActivity;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;
import com.jus.player.util.CommonUtils;
import com.jus.player.util.OptimizedGooglePay;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 充值页面
 */
public class VipRechargeActivity extends BaseActivity {

    // ------UI组件-----
    private ImageView vipRechargeBack;
    private LinearLayout vipMonth, vipSeason, vipYear;
    private Button btnVipOpen;

    // -----支付相关状态------
    private String selectedProductId;
    private int selectedAmount = 0;
    private View lastSelectedView = null;

    // -----Google支付实例-----
    private OptimizedGooglePay googlePay;

    // -----并发控制-----
    private final AtomicBoolean isPaymentInProgress = new AtomicBoolean(false);
    // 使用线程池处理网络请求
    private static final ExecutorService PAYMENT_EXECUTOR = Executors.newCachedThreadPool();
    // 使用ConcurrentHashMap管理订单锁
    private static final ConcurrentHashMap<String, Object> orderLocks = new ConcurrentHashMap<>();
    private final Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected int initLayout() {
        return R.layout.activity_vip_recharge;
    }

    @Override
    protected void initView() {
        vipRechargeBack = findViewById(R.id.vip_recharge_back);
        vipMonth = findViewById(R.id.vip_month);
        vipSeason = findViewById(R.id.vip_season);
        vipYear = findViewById(R.id.vip_year);
        btnVipOpen = findViewById(R.id.btn_vip_open);
        initClickListeners();
    }

    @Override
    protected void initData() {

        // 初始化计费
        googlePay = new OptimizedGooglePay(this);
        googlePay.setPayCallback(this::handlePaymentResult);

        TextView monthPrice = findViewById(R.id.month_price);
        TextView seasonPrice = findViewById(R.id.season_price);
        TextView yearPrice = findViewById(R.id.year_price);
        CommonUtils.ExchangeRateManager exchangeRateManager = new CommonUtils.ExchangeRateManager(this);
        monthPrice.setText(exchangeRateManager.getLocalPrice(30));
        seasonPrice.setText(exchangeRateManager.getLocalPrice(72));
        yearPrice.setText(exchangeRateManager.getLocalPrice(240));

        List<String> list = Arrays.asList(PRODUCT_ID_VIP_MONTH, PRODUCT_ID_VIP_SEASON, PRODUCT_ID_VIP_YEAR);
        //根据google play地区价格设置价格
        for (String value : list) {
            googlePay.queryProductPrice(value, new OkHttpHelper.HttpCallback() {
                @Override
                public void onSuccess(String response) {
                    runOnUiThread(() -> {
                        switch (value) {
                            case PRODUCT_ID_VIP_MONTH:
                                monthPrice.setText(response);
                                break;
                            case PRODUCT_ID_VIP_SEASON:
                                seasonPrice.setText(response);
                                break;
                            case PRODUCT_ID_VIP_YEAR:
                                yearPrice.setText(response);
                        }
                    });
                }

                @Override
                public void onFailure(OkHttpHelper.HttpException e) {

                }
            });
        }
    }

    private void initClickListeners() {
        vipRechargeBack.setOnClickListener(v -> finish());

        //vip类型选择
        vipMonth.setOnClickListener(v -> selectVIPType(v, PRODUCT_ID_VIP_MONTH, AppConfig.INT_30));
        vipSeason.setOnClickListener(v -> selectVIPType(v, PRODUCT_ID_VIP_SEASON, AppConfig.INT_72));
        vipYear.setOnClickListener(v -> selectVIPType(v, PRODUCT_ID_VIP_YEAR, AppConfig.INT_240));
        //开通vip按钮
        btnVipOpen.setOnClickListener(v -> {
            if (selectedProductId == null) {
                showToast(this, getString(R.string.hint_vip_select_type));
                return;
            }
            if (isPaymentInProgress.get()) {
                showToastPos(this, "正在处理支付，请稍候...", 300, false);
                return;
            }
            startPaymentProcess();
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 检查是否有未完成的支付
        googlePay.checkPendingPurchases();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //PAYMENT_EXECUTOR.shutdown();
        if (googlePay != null) {
            googlePay.destroy();
        }
    }

    // vip类型选择处理
    public void selectVIPType(View view, String productId, int amount) {
        if (lastSelectedView != null) {
            lastSelectedView.setBackgroundColor(ContextCompat.getColor(this, R.color.vip_bg));
        }
        // 设置点击的按钮的背景颜色
        //view.setBackgroundResource(R.drawable.bg_my_vip);
        view.setBackgroundColor(ContextCompat.getColor(this, R.color.yellow_start1));
        lastSelectedView = view;
        selectedAmount = amount;
        selectedProductId = productId;

        // 更新UI显示选中的金额
        updateSelectedAmountUI();
    }

    private void updateSelectedAmountUI() {
        String str = PRODUCT_ID_VIP_MONTH.equals(selectedProductId)
                ?  getString(R.string.monthly_plan)
                : (PRODUCT_ID_VIP_SEASON.equals(selectedProductId)
                ? getString(R.string.quarter_plan) : getString(R.string.annual_plan));
        String amountText = getString(R.string.recharge_amount_open_vip, selectedAmount, str);
        btnVipOpen.setText(amountText);
    }

    // 开始支付流程
    private void startPaymentProcess() {
        isPaymentInProgress.set(true);
        CommonUtils.showLoading(this);
        createOrder();
    }

    /**
     * 请求网络接口：创建订单
     */
    private void createOrder() {
        PAYMENT_EXECUTOR.execute(() -> {
            Map<String, String> params = new HashMap<>();
            params.put("productId", selectedProductId);
            OkHttpHelper.getInstance(this).getAsync(ApiConfig.CREATE_ORDER, params,
                    new OkHttpHelper.HttpCallback() {
                        @SuppressLint("NotifyDataSetChanged")
                        @Override
                        public void onSuccess(String res) {
                            JSONObject json = JSONObject.parseObject(res);
                            String orderId = json.getString(_DATA);
                            runOnUiThread(() -> googlePay.pay(orderId, selectedProductId));
                        }

                        @Override
                        public void onFailure(OkHttpHelper.HttpException e) {
                            runOnUiThread(() -> {
                                handlePaymentError(e.getMessage());
                            });
                        }
                    });
        });
    }

    // 处理支付结果
    public String handlePaymentResult(int payStatus, String orderCode) {
        runOnUiThread(() -> {
            switch (payStatus) {
                case AppConfig.PAY_OK:
                    handlePaymentSuccess(orderCode);
                    break;
                case AppConfig.PAY_FAILED:
                    handlePaymentFailure(orderCode, "订阅失败");
                    break;
                case AppConfig.PAY_CANCEL:
                    handlePaymentFailure(orderCode, "订阅已取消");
                    break;
                default:
                    handlePaymentFailure(orderCode, "未知订阅状态");
            }
        });
        return getStatusMessage(payStatus);
    }

    private String getStatusMessage(int payStatus) {
        switch (payStatus) {
            case AppConfig.PAY_OK:
                return "订阅成功" + selectedAmount + " dollar";
            case AppConfig.PAY_FAILED:
                return "订阅失败";
            case AppConfig.PAY_CANCEL:
                return "您已取消订阅";
            default:
                return "订阅状态未知";
        }
    }

    private void handlePaymentSuccess(String orderCode) {
        // 更新本地余额
        //int newBalance = balance.addAndGet(selectedAmount * 100);
        //balanceText.setText(String.valueOf(newBalance));
        // 更新订单状态
        updateOrder(orderCode, selectedAmount, AppConfig.INT_1);
        // 显示成功提示
        showToastPos(this, "订阅成功!", 300, true);
        resetPaymentState();
    }

    private void handlePaymentFailure(String orderCode, String errorMsg) {
        // 更新订单状态
        updateOrder(orderCode, selectedAmount,
                errorMsg.contains("取消") ? AppConfig.INT_2 : AppConfig.INT_1_);
        // 显示错误提示
        showToastPos(this, errorMsg, 300, true);
        resetPaymentState();
    }

    private void handlePaymentError(String errorMsg) {
        CommonUtils.hideLoading(this);
        showToastPos(this, "创建订单失败: " + errorMsg, 300, false);
        resetPaymentState();
    }

    //设置支付状态
    private void resetPaymentState() {
        isPaymentInProgress.set(false);
        CommonUtils.hideLoading(this);
    }

    /**
     * 支付完成，更新订单状态
     */
    private void updateOrder(String orderCode, int mAmount, int payOk) {
        //获取订单专用锁
        Object lock;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            /*
             * 1.如果orderCode不存在，则执行lambda创建新Object作为value
             * 2.如果已存在，直接返回已存在的value，整个过程是原子性的
             */
            lock = orderLocks.computeIfAbsent(orderCode, k -> new Object());
        } else {
            // 传统方式实现相同功能
            synchronized (orderLocks) {
                lock = orderLocks.get(orderCode);
                if (lock == null) {
                    lock = new Object();
                    orderLocks.put(orderCode, lock);
                }
            }
        }
        synchronized (lock) {
            try {
                Map<String, String> map = new HashMap<>();
                map.put("orderCode", orderCode);
                map.put("price", String.valueOf(mAmount));
                map.put("purchaseState", String.valueOf(payOk));
                OkHttpHelper.getInstance(this).getAsync(ApiConfig.UPDATE_ORDER_VIP, map, new OkHttpHelper.HttpCallback() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onSuccess(String res) {
                        Log.d("VIP订阅", "订单更新成功: " + orderCode);
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        Log.e("VIP订阅", "订单更新失败: " + e.getMessage());
                        runOnUiThread(() -> CommonUtils.showToastAsync(VipRechargeActivity.this, e.getMessage()));
                    }
                });
            } finally {
                orderLocks.remove(orderCode);
            }
        }

    }
}